<?php

class SearchFlight extends CI_Controller {

  public function index() {
    //$this->output->enable_profiler(TRUE);
    if (!$this->session->userdata('logged_in')) {
      redirect('login');
    }
    $this->form_validation->set_error_delimiters('<li>', '</li>');
    $this->form_validation->set_rules('from', $this->lang->line('from'), 'required|callback_airport_check');
    $this->form_validation->set_rules('to', $this->lang->line('to'), 'required|callback_airport_check');
    $this->form_validation->set_rules('depart_on', $this->lang->line('depart_on'), 'required|callback_date_check');
    if ($this->input->post('trip_type') === 'RT') {
      $this->form_validation->set_rules('return_on', $this->lang->line('return_on'), 'trim|callback_date_check|callback_date_prior');
    }
    $this->form_validation->set_rules('compare_from_to', $this->lang->line('from'), 'callback_compare_from_to');
    $this->form_validation->set_rules('trip_type', $this->lang->line('trip_type'), 'required');
    $this->form_validation->set_rules('adults', $this->lang->line('adult'), 'required|callback_max_pax');
    $this->form_validation->set_rules('children', $this->lang->line('child'), 'required|callback_only_child');
    $this->form_validation->set_rules('infants', $this->lang->line('infant'), 'trim|callback_infant_exceed');
    $this->form_validation->set_rules('students', $this->lang->line('student'), 'trim');
    $this->form_validation->set_rules('elders', $this->lang->line('elder'), 'trim');
    $this->form_validation->set_rules('military', $this->lang->line('elder'), 'trim');
    $this->form_validation->set_rules('cip', $this->lang->line('cip_service'), 'trim');

    /* TODO: add the remaining form attributes here */
    if ($this->form_validation->run() == FALSE) {
      $this->template->write('title', $this->lang->line('title_search_flight'));
      $this->template->write_view('left_side_bar_top', 'search_flight_form');
      /* TODO: change the replace function */
      $this->template->write_view('content', 'frontpages/frontpage');
      $this->template->render();
    } else {
      $search_form_array = array(
          'search_form_from' => $this->commonlibrary->get_port_code($this->commonlibrary->to_en_upper($this->input->post('from'))),
          'search_form_to' => $this->commonlibrary->get_port_code($this->commonlibrary->to_en_upper($this->input->post('to'))),
          'search_form_depart_on' => $this->commonlibrary->get_date_for_wd($this->input->post('depart_on')),
          'search_form_from_ui' => $this->input->post('from'),
          'search_form_to_ui' => $this->input->post('to'),
          'search_form_depart_on_ui' => $this->input->post('depart_on'),
          'search_form_trip_type' => $this->input->post('trip_type'),
          'search_form_adults' => $this->input->post('adults'),
          'search_form_children' => $this->input->post('children'),
          'search_form_infants' => $this->input->post('infants'),
          'search_form_students' => $this->input->post('students'),
          'search_form_elders' => $this->input->post('elders'),
          'search_form_military' => $this->input->post('military'),
          'search_form_cip' => ($this->input->post('cip')==1?1:0),
      );
      $this->session->set_userdata($search_form_array);

      $pax_count = $this->input->post('adults') + $this->input->post('children') + $this->input->post('infants') +
      $this->input->post('students') + $this->input->post('elders');

      $calculated_availability = $this->websdom_api->call_get_availability($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $this->session->userdata('search_form_from'), $this->session->userdata('search_form_to'), $this->session->userdata('search_form_depart_on'),$pax_count);
      $data['flight_depart'] = $this->get_availability_array_for_ui($calculated_availability,$this->input->post('depart_on'));

      if (strcmp($this->input->post('trip_type'), 'RT') == 0) {
        $search_form_array = array(
            'search_form_return_on' => $this->commonlibrary->get_date_for_wd($this->input->post('return_on')),
            'search_form_return_on_ui' => $this->input->post('return_on'),
        );
        $this->session->set_userdata($search_form_array);
        $calculated_availability = $this->websdom_api->call_get_availability($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $this->session->userdata('search_form_to'), $this->session->userdata('search_form_from'), $this->session->userdata('search_form_return_on'),$pax_count);
        $data['flight_return'] = $this->get_availability_array_for_ui($calculated_availability,$this->input->post('return_on'));
      }

      // old code, before template $this->load->view('search_flight_vi',$data);

      $this->template->write('title', $this->lang->line('title_availability'));
      $this->template->write_view('left_side_bar_top', 'search_flight_form');
      $this->template->write_view('left_side_bar_bottom', 'search_flight_notes');
      $this->template->write_view('content', 'search_flight_availability', $data);
      $this->template->render();
    }
  }

  function get_availability_array_for_ui($flight_details,$flight_date) {
    $now = time();$next_day='';
    $count_available_flight=0;
    $flights_to_display=array();
    foreach($flight_details as $flight) {
      $fare = $flight['fare'];
      $fdate = date("d-m-Y", strtotime($flight_date)) .' '. $this->commonlibrary->format_flighttime($flight['leg1']['departureTime']) . ':00';
      $fdiff=strtotime($fdate)-$now ;
      if ($fdiff > 10800) { // ucusa 3 saatten sonrasını göster
        $count_available_flight++;
        $total_legs=count($flight)-1;
        $key_bus='';$key_eco='';$key_ecr = '';
        if (isset($flight['leg1']['cabin_based_fares']['fare_BUS']['class']))
          $key_bus= $total_legs.'|'.$flight['leg1']['flightno'].'|'.$flight['leg1']['cabin_based_fares']['fare_BUS']['class'].'|'. $flight['leg1']["departureTime"].'|'.$flight['leg1']["origin"].'|'.$flight['leg1']["destination"].'|'.$flight['leg1']["isConnectedPrevSeg"];
        if (isset($flight['leg1']['cabin_based_fares']['fare_ECO']['class']))
          $key_eco = $total_legs.'|'.$flight['leg1']['flightno'].'|'.$flight['leg1']['cabin_based_fares']['fare_ECO']['class'].'|'. $flight['leg1']["departureTime"].'|'.$flight['leg1']["origin"].'|'.$flight['leg1']["destination"].'|'.$flight['leg1']["isConnectedPrevSeg"];
        if (isset($flight['leg1']['cabin_based_fares']['fare_ECR']['class']))
          $key_ecr = $total_legs.'|'.$flight['leg1']['flightno'].'|'.$flight['leg1']['cabin_based_fares']['fare_ECR']['class'].'|'. $flight['leg1']["departureTime"].'|'.$flight['leg1']["origin"].'|'.$flight['leg1']["destination"].'|'.$flight['leg1']["isConnectedPrevSeg"];
        if (isset($flight['leg2'])) {
          if (isset($flight['leg2']['cabin_based_fares']['fare_BUS']['class']))
            $key_bus= $key_bus.'|'.$flight['leg2']['flightno'].'|'.$flight['leg2']['cabin_based_fares']['fare_BUS']['class'].'|'. $flight['leg2']["departureTime"].'|'.$flight['leg2']["origin"].'|'.$flight['leg2']["destination"].'|'.$flight['leg2']["isConnectedPrevSeg"];
          if (isset($flight['leg2']['cabin_based_fares']['fare_ECO']['class']))
            $key_eco = $key_eco.'|'.$flight['leg2']['flightno'].'|'.$flight['leg2']['cabin_based_fares']['fare_ECO']['class'].'|'. $flight['leg2']["departureTime"].'|'.$flight['leg2']["origin"].'|'.$flight['leg2']["destination"].'|'.$flight['leg2']["isConnectedPrevSeg"];
          if (isset($flight['leg2']['cabin_based_fares']['fare_ECR']['class']))
            $key_ecr = $key_ecr.'|'.$flight['leg2']['flightno'].'|'.$flight['leg2']['cabin_based_fares']['fare_ECR']['class'].'|'. $flight['leg2']["departureTime"].'|'.$flight['leg2']["origin"].'|'.$flight['leg2']["destination"].'|'.$flight['leg2']["isConnectedPrevSeg"];
        }
        $total_amount_bus = $flight['leg1']['cabin_based_fares']['fare_BUS']['amount'];
        $total_amount_eco = $flight['leg1']['cabin_based_fares']['fare_ECO']['amount'];
        $total_amount_ecr = $flight['leg1']['cabin_based_fares']['fare_ECR']['amount'];
        if ((substr($flight['leg1']['departureTime'],-4,2)) > (substr($flight['leg1']['arrivalTime'],-4,2))) {
          $flight['leg1']['nextDay']='(e)';
        }
        if (isset($flight['leg2'])) {
          if ($flight['leg2']['cabin_based_fares']['fare_BUS']['amount'] > $flight['leg1']['cabin_based_fares']['fare_BUS']['amount'])
            $total_amount_bus = $flight['leg2']['cabin_based_fares']['fare_BUS']['amount'];
          if ($flight['leg2']['cabin_based_fares']['fare_ECO']['amount'] > $flight['leg1']['cabin_based_fares']['fare_ECO']['amount'])
            $total_amount_eco = $flight['leg2']['cabin_based_fares']['fare_ECO']['amount'];
          if ($flight['leg2']['cabin_based_fares']['fare_ECR']['amount'] > $flight['leg1']['cabin_based_fares']['fare_ECR']['amount'])
            $total_amount_ecr = $flight['leg2']['cabin_based_fares']['fare_ECR']['amount'];
          if ((substr($flight['leg2']['departureTime'],-4,2)) > (substr($flight['leg2']['arrivalTime'],-4,2))) {
            $flight['leg2']['nextDay']='(e)';
          }
          if ((substr($flight['leg1']['arrivalTime'],-4,2)) > (substr($flight['leg2']['departureTime'],-4,2))) {
            $flight['leg2']['nextDay']='(e)';
          }
        }

        $total_amount_bus += $fare['tax_VQ'] + $fare['tax_YR'];
        $total_amount_eco += $fare['tax_VQ'] + $fare['tax_YR'];
        $total_amount_ecr += $fare['tax_VQ'] + $fare['tax_YR'];

        $total_amount_bus = ($total_amount_bus>999999)?0:$total_amount_bus;
        $total_amount_eco = ($total_amount_eco>999999)?0:$total_amount_eco;
        $total_amount_ecr = ($total_amount_ecr>999999)?0:$total_amount_ecr;

        array_push($flights_to_display,array('flight'=>$flight,'key_bus'=> $key_bus,'key_eco'=> $key_eco,'key_ecr'=> $key_ecr,'total_amount_bus'=>$total_amount_bus,'total_amount_eco'=>$total_amount_eco,'total_amount_ecr'=>$total_amount_ecr));
      }
    }
    return $flights_to_display;
  }

  public function compare_from_to() {
    if (strcmp($this->input->post('from'), $this->input->post('to')) == 0) {
      $this->form_validation->set_message('compare_from_to', $this->lang->line('compare_from_to'));
      return FALSE;
    } else {
      return TRUE;
    }
  }

  function date_check($value) {
    $ddmmyy = '(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19|20)[0-9]{2}';
    if (preg_match("/$ddmmyy$/", $value)) {
      return TRUE;
    } else {
      $this->form_validation->set_message('date_check', $this->lang->line('date_check'));
      return FALSE;
    }
  }

  function date_prior() {
    $departdate = strtotime($this->input->post('depart_on'));
    $returndate = strtotime($this->input->post('return_on'));
    if ($departdate > $returndate) {
      $this->form_validation->set_message('date_prior', $this->lang->line('date_check'));
      return FALSE;
    }
    return TRUE;
  }

  function airport_check($value) {
    $value = $this->commonlibrary->get_port_code($this->commonlibrary->to_en_upper($value));
    if (!array_key_exists($value, $this->commonlibrary->portlist)) {
      $this->form_validation->set_message('airport_check', $this->lang->line('airport_check', $value));
      return FALSE;
    }
    return TRUE;
  }

  function infant_exceed() {
    $sum_adults = $this->input->post('adults') + $this->input->post('elders');
    if ($sum_adults < $this->input->post('infants')) {
      $this->form_validation->set_message('infant_exceed', $this->lang->line('infant_exceed'));
      return FALSE;
    }
    return TRUE;
  }

  function only_child() {
    $sum_adults = $this->input->post('adults') + $this->input->post('elders') + $this->input->post('students');
    if ($sum_adults == 0) {
      $this->form_validation->set_message('only_child', $this->lang->line('only_child'));
      return FALSE;
    }
    return TRUE;
  }

  function max_pax() {
    $sum_pax = $this->input->post('adults') + $this->input->post('children') +
    $this->input->post('infants') + $this->input->post('students') +
    $this->input->post('elders');
    if ($sum_pax > 4) {
      $this->form_validation->set_message('max_pax', $this->lang->line('max_pax'));
      return FALSE;
    }
    return TRUE;
  }
}